# -*- coding: utf-8 -*-
"""
@File    : ningxia_yinchuan_jfqu_policy
@Author  : caojy
"""
import datetime
import json
import math

import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item, urllib
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class NingxiaYinchuanQuPolicy(BaseTaxPolicySpider):
    name = 'ningxia_yinchuan_jfqu_policy'

    province = '宁夏回族自治区'
    city = '银川市'
    county = ''
    park = ''

    def start_requests(self):
        for source, county, url in [
            ['金凤区人民政府', '金凤区', 'http://www.ycjinfeng.gov.cn/xxgk/zc/xzgfxwj/qzf/'],
            ['金凤区人民政府', '金凤区', 'http://www.ycjinfeng.gov.cn/xxgk/zc/xzgfxwj/qzfb/'],
            ['金凤区人民政府', '金凤区', 'http://www.ycjinfeng.gov.cn/xxgk/zc/zfwj/bmwj/'],
            ['金凤区政府办公室', '金凤区', 'http://www.ycjinfeng.gov.cn/xxgk/xxgkbm/jfqzfbgs/xxgkmn/zcfg_18885/'],
            ['金凤区发展和改革局', '金凤区', 'http://www.ycjinfeng.gov.cn/xxgk/xxgkbm/jfqjjfzj/xxgkml_18908/bmwj_18910/'],
            ['金凤区工业信息化和科学技术局', '金凤区', 'http://www.ycjinfeng.gov.cn/xxgk/xxgkbm/jfqswj_19805/xxgkml_19670/bmwj_19672/'],
            ['金凤区财政局', '金凤区', 'http://www.ycjinfeng.gov.cn/xxgk/xxgkbm/jfqczj/xxgkml_18977/bmwj_18979/'],
            ['金凤区人力资源和社会保障局', '金凤区', 'http://www.ycjinfeng.gov.cn/xxgk/xxgkbm/jfqrlzyhshbzj/xxgkml_18991/bmwj_18993/'],
            ['金凤区商务和投资促进局', '金凤区', 'http://www.ycjinfeng.gov.cn/xxgk/xxgkbm/jfqswj/xxgkml_19670/bmwj_19672/'],
            ['金凤区文化旅游体育广电局', '金凤区', 'http://www.ycjinfeng.gov.cn/xxgk/xxgkbm/jfqwtlyj/xxgkml_19054/bmwj_19056/'],
            ['西夏区人民政府', '西夏区', 'http://www.ycxixia.gov.cn/zwgk/zc/xzgfxwj_72275/qzf_72276/'],
            ['西夏区人民政府', '西夏区', 'http://www.ycxixia.gov.cn/zwgk/zc/xzgfxwj_72275/qzfb/'],
            ['西夏区人民政府', '西夏区', 'http://www.ycxixia.gov.cn/zwgk/zc/zfwj/bmwj/index.html'],
            ['西夏区发展和改革局', '西夏区', 'http://www.ycxixia.gov.cn/zwgk/bmxxgkmn/xxqjjfzj/fdzdgknr_48510/bmwj_9829/'],
            ['西夏区工业信息化和科学技术局', '西夏区', 'http://www.ycxixia.gov.cn/zwgk/bmxxgkmn/xxqkjj/fdzdgknr_48510/bmwj_9860/'],
            ['西夏区财政局', '西夏区', 'http://www.ycxixia.gov.cn/zwgk/bmxxgkmn/xxqczj/fdzdgknr_48521/bmwj_9906/'],
            ['西夏区人力资源和社会保障局', '西夏区', 'http://www.ycxixia.gov.cn/zwgk/bmxxgkmn/xxqrlzyhshbzj/fdzdgknr_48521/bmwj_9920/'],
            ['西夏区商务和投资促进局', '西夏区', 'http://www.ycxixia.gov.cn/zwgk/bmxxgkmn/xxqsmwlyjhzj/fdzdgknr_48521/bmwj_10064/'],
            ['西夏区文化旅游体育广电局', '西夏区', 'http://www.ycxixia.gov.cn/zwgk/bmxxgkmn/xxqwhtylyj/fdzdgknr_48521/bmwj_10048/'],
        ]:
            url = url.replace("/zc.html", "/index.html")
            if 'index.html' not in url:
                url += 'index.html'
            item = {'source': source, 'county': county}
            yield scrapy.Request(url, callback=self.parse_list, meta={"item": item})

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        for elem in response.xpath(
            "//tr[@class='zcwjk-list-c clearfix']//td/a[not(contains(@href, 'zcjd_'))]/ancestor::td[string-length(string(.))>=10] | "
            "//div[@class='zfxxgk_zdgkc']//li/a[not(contains(@href, 'zcjd_'))]/ancestor::li[string-length(string(.))>=10]"
        ):
            item = Item()
            item['source_url'] = elem.xpath(""".//a/@href""").re_first(r"""(.*/.*)""")
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem.xpath("""string(.)""").get()
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            # if '.htm' not in item['source_url'] and '.shtm' not in item['source_url'] and '.jhtm' not in item['source_url']:
            #     continue
            print(response.url, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            total_page = response.xpath(""".""").re_first(r"""countPage\s*=\s*(\d+)""") or response.xpath(""".""").re_first(r"createPage.*?\((\d+)")
            print(response.url, "page:", total_page)
            for page_num in range(1, int(int(total_page) / 1)):
                yield response.follow(response.url.replace("/index.html", f"/index_{page_num}.html"),
                                      callback=self.parse_list, meta={'item': prev_item, 'is_next': False})

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get() or response.xpath("//*[@class='fbrq']/text()").get()
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl ningxia_yinchuan_jfqu_policy".split())
